// controllers/pointController.js
const { pool } = require('../config/db');

// 1. 查用户积分变动记录（核心：用户能看到自己赚了多少、花了多少）
exports.getUserPointHistory = async (req, res, next) => {
  try {
    const { userId } = req.params;
    const { page = 1, limit = 10, type } = req.query; // type：income（收入）/expense（支出）
    const offset = (page - 1) * limit;

    // 验证权限：只能查自己的积分记录（当前登录用户ID = 路由中的userId）
    if (parseInt(req.user.id) !== parseInt(userId)) {
      const error = new Error('没有权限查看他人的积分记录');
      error.statusCode = 403;
      throw error;
    }

    // 构建查询条件（支持按类型筛选：收入/支出）
    let query = `
      SELECT pr.*, g.name as goods_name 
      FROM point_records pr
      LEFT JOIN goods g ON pr.goods_id = g.id  -- 兑换商品时关联商品名称
      WHERE pr.user_id = ? 
    `;
    const queryParams = [userId];

    // 如果传了type，增加筛选条件
    if (type === 'income' || type === 'expense') {
      query += `AND pr.type = ? `;
      queryParams.push(type);
    }

    // 排序+分页
    query += `ORDER BY pr.created_at DESC LIMIT ? OFFSET ?`;
    queryParams.push(parseInt(limit), parseInt(offset));

    // 执行查询
    const [history] = await pool.query(query, queryParams);

    // 查总记录数（用于分页）
    let countQuery = `SELECT COUNT(*) as total FROM point_records WHERE user_id = ?`;
    const countParams = [userId];
    if (type === 'income' || type === 'expense') {
      countQuery += ` AND type = ?`;
      countParams.push(type);
    }
    const [countResult] = await pool.query(countQuery, countParams);
    const total = parseInt(countResult[0].total);

    res.status(200).json({
      success: true,
      count: history.length,
      total,
      totalPages: Math.ceil(total / limit),
      currentPage: parseInt(page),
      data: history
    });
  } catch (err) {
    next(err);
  }
};

// 2. 查用户积分汇总（当前剩余积分 + 总获得积分 + 总支出积分）
exports.getPointSummary = async (req, res, next) => {
  try {
    const { userId } = req.params;

    // 验证权限：只能查自己的汇总
    if (parseInt(req.user.id) !== parseInt(userId)) {
      const error = new Error('没有权限查看他人的积分汇总');
      error.statusCode = 403;
      throw error;
    }

    // 1. 查当前剩余积分（从users表获取）
    const [user] = await pool.query(
      'SELECT points FROM users WHERE id = ?',
      [userId]
    );
    if (user.length === 0) {
      const error = new Error('用户不存在');
      error.statusCode = 404;
      throw error;
    }
    const currentPoints = parseInt(user[0].points);

    // 2. 查总获得积分（type=income的总和）
    const [totalIncome] = await pool.query(
      'SELECT IFNULL(SUM(amount), 0) as total FROM point_records WHERE user_id = ? AND type = ?',
      [userId, 'income']
    );

    // 3. 查总支出积分（type=expense的总和）
    const [totalExpense] = await pool.query(
      'SELECT IFNULL(SUM(amount), 0) as total FROM point_records WHERE user_id = ? AND type = ?',
      [userId, 'expense']
    );

    res.status(200).json({
      success: true,
      data: {
        userId: parseInt(userId),
        currentPoints, // 当前剩余积分
        totalIncome: parseInt(totalIncome[0].total), // 总获得积分
        totalExpense: parseInt(totalExpense[0].total), // 总支出积分
        totalEarned: parseInt(totalIncome[0].total) - parseInt(totalExpense[0].total) // 净赚积分（校验用）
      }
    });
  } catch (err) {
    next(err);
  }
};

// 3. 积分兑换商品（核心功能：扣减积分+生成兑换记录）
exports.exchangeGoods = async (req, res, next) => {
  try {
    const { goodsId } = req.body;
    const userId = req.user.id; // 当前登录用户ID（从JWT中获取，无需前端传）

    // 1. 查商品是否存在 + 商品积分价格
    const [goods] = await pool.query(
      'SELECT id, name, point_price, stock FROM goods WHERE id = ? AND stock > 0',
      [goodsId]
    );
    if (goods.length === 0) {
      const error = new Error('商品不存在或已售罄');
      error.statusCode = 404;
      throw error;
    }
    const { name: goodsName, point_price: requiredPoints, stock } = goods[0];

    // 2. 查用户当前积分是否足够
    const [user] = await pool.query(
      'SELECT points FROM users WHERE id = ?',
      [userId]
    );
    const currentPoints = parseInt(user[0].points);
    if (currentPoints < requiredPoints) {
      const error = new Error(`积分不足！需要 ${requiredPoints} 积分，当前仅 ${currentPoints} 积分`);
      error.statusCode = 400;
      throw error;
    }

    // 3. 开启事务（确保“扣积分+减库存+记记录”三步同时成功/失败，避免数据不一致）
    const connection = await pool.getConnection();
    try {
      await connection.beginTransaction(); // 开始事务

      // 3.1 扣减用户积分
      await connection.query(
        'UPDATE users SET points = points - ?, updated_at = NOW() WHERE id = ?',
        [requiredPoints, userId]
      );

      // 3.2 减少商品库存
      await connection.query(
        'UPDATE goods SET stock = stock - 1, updated_at = NOW() WHERE id = ? AND stock > 0',
        [goodsId]
      );

      // 3.3 记录积分支出记录（type=expense，关联商品ID）
      const [recordResult] = await connection.query(
        `INSERT INTO point_records 
         (user_id, type, amount, goods_id, description, created_at) 
         VALUES (?, ?, ?, ?, ?, NOW())`,
        [userId, 'expense', requiredPoints, goodsId, `兑换商品：${goodsName}`]
      );

      await connection.commit(); // 提交事务

      // 4. 返回兑换结果（含更新后的积分）
      const [updatedUser] = await pool.query(
        'SELECT points FROM users WHERE id = ?',
        [userId]
      );

      res.status(200).json({
        success: true,
        message: `兑换成功！已扣除 ${requiredPoints} 积分`,
        data: {
          exchangeRecordId: recordResult.insertId, // 兑换记录ID
          goods: { id: goodsId, name: goodsName }, // 兑换的商品
          remainingPoints: parseInt(updatedUser[0].points) // 兑换后剩余积分
        }
      });
    } catch (transErr) {
      await connection.rollback(); // 事务失败，回滚所有操作
      throw transErr; // 抛出错误，让全局错误中间件处理
    } finally {
      connection.release(); // 释放数据库连接
    }
  } catch (err) {
    next(err);
  }
};